<template>
  <div>
    <n-card
      :bordered="false"
      title="用户基本信息"
      class="mt-4 proCard"
      size="small"
      :segmented="{ content: 'hard' }"
    >
      <n-space justify="center">
        <n-grid cols="2 s:2 m:2 l:3 xl:3 2xl:3" responsive="screen">
          <n-grid-item>
            <n-form :label-width="80" label-placement="left" :model="userModel" :rules="rules"
                    ref="formRef">
              <n-form-item label="用户" path="name">
                <span v-text="userModel.name"/>
              </n-form-item>

              <n-form-item label="姓名" path="realName">
                <n-input placeholder="请输入姓名" v-model:value="userModel.realName"/>
              </n-form-item>

              <n-form-item label="角色名称" path="desc">
                <n-input placeholder="请输入角色名称" v-model:value="userModel.desc"/>
              </n-form-item>

              <n-form-item label="原密码" path="password">
                <n-input v-model:value="userModel.password"
                         type="password"
                         placeholder="请输入原密码"/>
              </n-form-item>
              <n-form-item label="修改密码" path="newPassword">
                <n-input v-model:value="userModel.newPassword"
                         type="password"
                         :disabled="!userModel.password"
                         @input="handlePasswordInput"
                         @keydown.enter.prevent
                         placeholder="请输入新密码"/>
              </n-form-item>
              <n-form-item ref="rPasswordFormItemRef"
                           first
                           label="确认密码"
                           path="confirmPassword">
                <n-input v-model:value="userModel.confirmPassword"
                         :disabled="!userModel.newPassword"
                         type="password"
                         @keydown.enter.prevent
                         placeholder="请输入确认密码"/>
              </n-form-item>
              <div>
                <n-space justify="space-around">
                  <n-button type="warning" @click="resetForm">重置</n-button>
                  <n-button type="primary" @click="formSubmit">修改</n-button>
                </n-space>
              </div>
            </n-form>
          </n-grid-item>
        </n-grid>
      </n-space>
    </n-card>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref, unref} from 'vue';
import {FormInst, FormItemInst, FormRules, useMessage} from 'naive-ui';
import {useUserStore} from "@/store/modules/user";
import {changePassword, userUpdate} from "@/api/system/user";
import {ResultEnum} from "@/enums/httpEnum";
import {HmacSHA512} from "@/utils/crypto";

interface UserInfo {
  name: string | null;
  realName: string | null;
  desc: string | null;
  password: string | null;
  newPassword: string | null;
  confirmPassword: string | null;
}

interface UserParams {
  name: string | null;
  realName: string | null;
  desc: string | null;
  password: string | null;
  newPassword: string | null;
}

const formRef = ref<FormInst | null>(null);
const useMsg = useMessage();

const rPasswordFormItemRef = ref<FormItemInst | null>(null)
const userStore = useUserStore();

const userModel = ref<UserInfo>({
  name: null,
  realName: null,
  desc: null,
  password: null,
  newPassword: null,
  confirmPassword: null,
});

const rules: FormRules = {
  realName: {
    required: true,
    message: '请输入姓名',
    trigger: 'blur',
  },
  desc: {
    required: true,
    message: '请输入角色名称',
    trigger: 'input',
  },
  password: {
    required:true,
    message: '请输入密码',
    trigger: 'input',
  },
  newPassword: [
    {
      message: '请输入新密码',
      trigger: 'input',
      min:6,
      max:36
    }
  ],
  confirmPassword: [
    {
      message: '请再次输入密码',
      trigger: ['input', 'blur']
    },
    {
      validator: (rule, value) => {
        if (userModel.value.newPassword != null && userModel.value.password != null) {
          return (!!userModel.value.newPassword &&
            userModel.value.newPassword.startsWith(value) &&
            userModel.value.newPassword.length >= value.length);
        }
        return true;

      },
      message: '两次输入密码不一致',
      trigger: 'input'
    },
    {
      validator: (rule, value) => {
        return value === userModel.value.newPassword;
      },
      message: '两次输入密码不一致!',
      trigger: ['blur', 'password-input']
    }
  ],
};

function initUserInfo() {
  const userInfo = userStore.getUserInfo;
  const {userId, username, realName, desc} = userInfo as any;
  userModel.value.name = username;
  userModel.value.realName = realName;
  userModel.value.desc = desc;
  userModel.value.password = null;
  userModel.value.newPassword = null;
  userModel.value.confirmPassword = null;
}

onMounted(() => {
  initUserInfo();
});

function handlePasswordInput() {
  if (userModel.value.confirmPassword) {
    rPasswordFormItemRef.value?.validate({trigger: 'password-input'})
  }
}

function resetForm() {
  formRef.value?.restoreValidation();
  initUserInfo();
}

function formSubmit() {
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      useMsg.success('验证成功');
      const params: UserParams = {
        name: userModel.value.name,
        realName: userModel.value.realName,
        desc: userModel.value.desc,
        password: userModel.value.password!=null?HmacSHA512(userModel.value.password):null,
        newPassword: userModel.value.confirmPassword!=null?HmacSHA512(userModel.value.confirmPassword):null
      };
      const {code, message} = await userUpdate(params)
      if (code == ResultEnum.SUCCESS) {
        useMsg.success(`${message}`);
        await userStore.GetInfo();
      } else {
        useMsg.error(`错误：${message}`);
      }
    } else {
      useMsg.error('验证失败，请填写完整信息');
    }
  });
}
</script>
